<template>
  <div class="image-container">
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="图片类型">
          <el-input
            v-model="queryParams.type"
            placeholder="请输入图片类型"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-container">
      <div class="top-actions">
        <el-button type="primary" @click="handleUpload">上传图片</el-button>
      </div>

      <el-table
        :data="imageList"
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="type" label="图片类型" width="120">
          <template #default="scope">
            {{ scope.row.type || "无类型" }}
          </template>
        </el-table-column>
        <el-table-column label="图片预览" width="200">
          <template #default="scope">
            <el-image
              :src="IMAGE_SERVER + scope.row.url"
              :preview-src-list="[IMAGE_SERVER + scope.row.url]"
              fit="cover"
              style="width: 100px; height: 100px; border-radius: 4px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="url" label="图片链接" show-overflow-tooltip>
          <template #default="scope">
            <el-link
              type="primary"
              :href="IMAGE_SERVER + scope.row.url"
              target="_blank"
            >
              {{ IMAGE_SERVER + scope.row.url }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="上传时间" width="170">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handlePreview(scope.row)"
            >
              预览
            </el-button>
            <el-popconfirm
              title="确定要删除这张图片吗？"
              @confirm="handleDelete(scope.row)"
            >
              <template #reference>
                <el-button type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 上传图片对话框 -->
    <el-dialog
      title="上传图片"
      v-model="uploadDialogVisible"
      width="500px"
      append-to-body
    >
      <el-form
        ref="uploadFormRef"
        :model="uploadForm"
        :rules="uploadRules"
        label-width="100px"
      >
        <el-form-item label="图片类型" prop="type">
          <el-input
            v-model="uploadForm.type"
            placeholder="请输入图片类型，例如：轮播图、头像等"
          />
        </el-form-item>
        <el-form-item label="图片文件" prop="images">
          <ImageUploader
            v-model="uploadForm.images"
            :limit="5"
            :type="uploadForm.type"
            @upload-success="handleUploadSuccess"
            @upload-error="handleUploadError"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="uploadDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog
      title="图片预览"
      v-model="previewDialogVisible"
      width="60%"
      append-to-body
    >
      <div class="preview-container">
        <el-image
          :src="IMAGE_SERVER + previewUrl"
          fit="contain"
          style="width: 100%; max-height: 60vh"
        />
        <div class="image-info">
          <p><strong>ID:</strong> {{ previewImage.id }}</p>
          <p><strong>类型:</strong> {{ previewImage.type || "无类型" }}</p>
          <p>
            <strong>上传时间:</strong> {{ formatDate(previewImage.createTime) }}
          </p>
          <p>
            <strong>图片链接:</strong>
            <el-link
              type="primary"
              :href="IMAGE_SERVER + previewImage.url"
              target="_blank"
            >
              {{ IMAGE_SERVER + previewImage.url }}
            </el-link>
          </p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import ImageUploader from "@/components/ImageUploader.vue";
import { getImageList, deleteImage } from "@/api/image";

const IMAGE_SERVER = process.env.VUE_APP_IMAGE_SERVER;

console.log("图片服务器地址:", IMAGE_SERVER);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  type: "",
});

const loading = ref(false);
const total = ref(0);
const imageList = ref([]);

// 上传表单相关
const uploadDialogVisible = ref(false);
const uploadFormRef = ref();
const uploadForm = reactive({
  type: "",
  images: [],
});

// 上传表单校验规则
const uploadRules = {
  type: [{ max: 50, message: "图片类型最多50个字符", trigger: "blur" }],
};

// 预览相关
const previewDialogVisible = ref(false);
const previewUrl = ref("");
const previewImage = reactive({
  id: null,
  url: "",
  type: "",
  createTime: null,
});

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return "-";
  const date = new Date(dateString);
  return date.toLocaleString(); // 显示日期和时间
};

// 查询图片列表
const getImages = async () => {
  loading.value = true;
  try {
    const { pageNum, pageSize, type } = queryParams;
    let params = { pageNum, pageSize };

    if (type) params.type = type;

    const response = await getImageList(params);

    if (response.code === 200 && response.data) {
      imageList.value = response.data.list;
      total.value = response.data.total;
    } else {
      ElMessage.error(response.message || "获取图片列表失败");
    }
  } catch (error) {
    console.error("查询图片列表出错:", error);
    ElMessage.error("查询图片列表出错");
  } finally {
    loading.value = false;
  }
};

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1;
  getImages();
};

// 重置按钮
const resetQuery = () => {
  queryParams.type = "";
  handleQuery();
};

// 上传图片
const handleUpload = () => {
  uploadForm.type = "";
  uploadForm.images = [];
  uploadDialogVisible.value = true;
};

// 图片上传成功回调
const handleUploadSuccess = (image) => {
  ElMessage.success("上传成功");
  getImages(); // 刷新列表
};

// 图片上传失败回调
const handleUploadError = (error) => {
  ElMessage.error("上传失败：" + (error.message || "未知错误"));
};

// 预览图片
const handlePreview = (row) => {
  previewUrl.value = row.url;
  Object.assign(previewImage, row);
  previewDialogVisible.value = true;
};

// 删除图片
const handleDelete = async (row) => {
  try {
    const response = await deleteImage(row.id);

    if (response.code === 200) {
      ElMessage.success("删除成功");
      getImages(); // 刷新列表
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error) {
    console.error("删除图片出错:", error);
    ElMessage.error("删除图片出错");
  }
};

// 分页
const handleSizeChange = (val) => {
  queryParams.pageSize = val;
  getImages();
};

const handleCurrentChange = (val) => {
  queryParams.pageNum = val;
  getImages();
};

// 初始化
onMounted(() => {
  getImages();
});
</script>

<style lang="scss" scoped>
.image-container {
  padding: 10px;

  .filter-container {
    margin-bottom: 20px;
  }

  .table-container {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .top-actions {
      margin-bottom: 20px;

      .el-button {
        margin-right: 10px;
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }

  .preview-container {
    display: flex;
    flex-direction: column;
    gap: 20px;

    .image-info {
      margin-top: 20px;
      background-color: #f5f7fa;
      padding: 15px;
      border-radius: 4px;

      p {
        margin: 5px 0;
      }
    }
  }
}
</style>
